import minimist from 'minimist';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
import esbuild from 'esbuild';
// node中的命令函参数通过process 来获取 process.argv
const args = minimist(process.argv.slice(2));

// esm 使用commonjs 变量
const __filename = fileURLToPath(import.meta.url); // 获取文件的绝对路径 file: -> /usr
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);
const target = args._[0] || 'reactivity';
const format = args.f || 'esm';
// 入口文件 根据命令行提供的路径来进行解析
const pkg = require(`../packages/${target}/package.json`);
const entry = resolve(__dirname, `../packages/${target}/src/index.ts`);
const outfile = resolve(
  __dirname,
  `../packages/${target}/dist/${target}.${format}.js`
);
// 打包配置信息
const buildOptions = {
  entryPoints: [entry],
  outfile,
  bundle: true,
  platform: 'browser',
  sourcemap: true,
  format, // cjs esm iife
  globalName: pkg.buildOptions?.name,
};
console.log('buildOptions', buildOptions);
esbuild.context(buildOptions).then((ctx) => {
  console.log('start dev', ctx);
  return ctx.watch(); // 监控入口文件持续进行打包处理
});
